/*
 * Copyright (C) 2020 唐家林
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package main

import (
	"flag"
	"fmt"
	"github.com/sudot/trayhost"
	"github.com/sudot/yapi-tools/internal"
	"github.com/sudot/yapi-tools/internal/assets"
	"github.com/sudot/yapi-tools/internal/logger"
	"github.com/sudot/yapi-tools/internal/server"
	"os/exec"
	"runtime"
)

func init() {
	h := *flag.Bool("h", false, "显示帮助信息")
	internal.Port = *flag.Int("p", 18080, "`port` 端口号")
	if h {
		flag.Usage()
	}
	internal.Url = fmt.Sprintf("http://localhost:%d", internal.Port)
}

func main() {
	// EnterLoop must be called on the OS's main thread
	runtime.LockOSThread()

	trayhost.Initialize(internal.AppName, onClick)
	trayhost.SetIconData(assets.IconData)
	trayhost.SetMenu(trayhost.MenuItems{
		trayhost.NewMenuItem("打开", onClick),
		trayhost.NewMenuItemDivided(),
		trayhost.NewMenuItem("退出", trayhost.Exit),
	})

	go server.RunServer(internal.Port)

	// Enter the host system's event loop
	trayhost.EnterLoop()

	// This is only reached once the user chooses the Exit menu item
	logger.Info("Exiting")
}

func onClick() {
	var commands = map[string]string{
		"windows": "explorer",
		"darwin":  "open",
		"linux":   "xdg-open",
	}
	run, _ := commands[runtime.GOOS]
	_ = exec.Command(run, internal.Url).Start()

}
